package com.coder.rental.utils;

import cn.hutool.core.convert.NumberWithFormat;
import cn.hutool.core.date.DateTime;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTPayload;
import cn.hutool.jwt.JWTUtil;
import org.springframework.stereotype.Component;

import java.util.HashMap;
import java.util.Map;

/**
 * @author student_Hao
 * @project auto_rental
 * @date 2025/11/2
 */
@Component
public class JwtUtils {
    public static final String SECRET_KEY = "student_hao";
    public static final long EXPIRATION_TIME = 1000L*60*30;
    public static String createToken(Map<String, Object> payload) {
        DateTime now = DateTime.now();
        DateTime newTime = new DateTime(now.getTime()+EXPIRATION_TIME);
        payload.put(JWTPayload.ISSUED_AT,now);
        payload.put(JWTPayload.EXPIRES_AT,newTime);
        payload.put(JWTPayload.NOT_BEFORE,now);
        return JWTUtil.createToken(payload,SECRET_KEY.getBytes());
    }

    public static JWTPayload parseToken(String token) {
        JWT jwt = JWTUtil.parseToken(token);
        if (!jwt.setKey(SECRET_KEY.getBytes()).verify()){
            throw new RuntimeException("token异常");
        }
        if (!jwt.validate(0)){
            throw new RuntimeException("token已过期");
        }
        return jwt.getPayload();
    }

    public static void main(String[] args) {
        /*Map<String, Object> payload = new HashMap<>();
        payload.put("username","admin");
        payload.put("id","111");
        String token = createToken(payload);
        System.out.println(token);*/
        String token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJuYmYiOjE3NjIwMTM3MzMsImlkIjoiMTExIiwiZXhwIjoxNzYyMDE1NTMzLCJpYXQiOjE3NjIwMTM3MzMsInVzZXJuYW1lIjoiYWRtaW4ifQ.B8jelnT_QeXPaE-9T7jKwcYKZiyOaae7CInD3mqOGk0";
        JWTPayload payload = parseToken(token);
        System.out.println(payload.getClaim("username"));
        System.out.println(payload.getClaim("id"));
        NumberWithFormat claim = (NumberWithFormat) payload.getClaim(JWTPayload.EXPIRES_AT);
        DateTime convert = (DateTime) claim.convert(DateTime.class, claim);
        long expireTime = convert.getTime();
        long nowTime = DateTime.now().getTime();
        System.out.println((expireTime-nowTime)/1000);
    }
}
